package com.suda.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.suda.constant.MessageConstant;
import com.suda.constant.PasswordConstant;
import com.suda.constant.StatusConstant;
import com.suda.context.BaseContext;
import com.suda.dto.EmployeeDTO;
import com.suda.dto.EmployeeLoginDTO;
import com.suda.dto.EmployeePageQueryDTO;
import com.suda.dto.PasswordEditDTO;
import com.suda.entity.Employee;
import com.suda.exception.AccountLockedException;
import com.suda.exception.AccountNotFoundException;
import com.suda.exception.PasswordErrorException;
import com.suda.mapper.EmployeeMapper;
import com.suda.result.PageResult;
import com.suda.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Properties;
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    private Properties pageHelperProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /**
     * 新增员工
     * @param employeeDTO
     */
    public void save(EmployeeDTO employeeDTO) {
        //System.out.println("当前线程的id:" + Thread.currentThread().getId());
        Employee employee = new Employee();
        // 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置账号的状态，默认正常状态 1表示正常
        employee.setStatus(StatusConstant.ENABLE);

        // 设置密码，默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录创建时间与修改时间 创建人id与修改人id(公共字段自动填充，进行统一处理)

        employeeMapper.insert(employee);

    }

    /**
     * 分页查询员工信息
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page =  employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee= Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        // 密码设置为******,加强安全性
        employee.setPassword("******");
        return employee;
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置当前记录修改时间 修改人id(公共字段自动填充)

        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     * @return
     */
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //获取当前登录用户的id
        Long empId = BaseContext.getCurrentId();
        //就可以查到数据库的用户信息
        Employee employee = employeeMapper.getById(empId);
        //当前 前端传过来的oldPassword进行md5加密后
        String pwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //进行对比
        if (!pwd.equals(employee.getPassword())) {
            //原密码错误
            throw new PasswordErrorException("原密码错误");
        }
        //如果输入的原密码与数据库密码相同，则进行修改，把newPassword进行MD5加密存入数据库，密码修改成功
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    /**
     * 删除员工
     * @param id
     */


    @Override
    public void deleteById(Long id) {
        // 调用 EmployeeMapper 的 deleteById 方法来删除员工
        employeeMapper.deleteById(id);
    }
}
